package com.test.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * MyBatis工具类
 * 提供SqlSession的创建和管理
 */
public class MyBatisUtil {
    
    private static SqlSessionFactory sqlSessionFactory;
    
    // 静态代码块，初始化SqlSessionFactory
    static {
        try {
            // 加载MyBatis配置文件
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            
            // 创建SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            
            System.out.println("✅ MyBatis SqlSessionFactory 初始化成功！");
            
        } catch (IOException e) {
            throw new RuntimeException("MyBatis初始化失败", e);
        }
    }
    
    /**
     * 获取SqlSession
     * @return SqlSession对象
     */
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true); // 自动提交
    }
    
    /**
     * 获取SqlSession（自动提交）
     * @return SqlSession对象
     */
    public static SqlSession getSqlSession(boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit);
    }
    
    /**
     * 关闭SqlSession
     * @param sqlSession SqlSession对象
     */
    public static void closeSqlSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
    
    /**
     * 获取SqlSessionFactory
     * @return SqlSessionFactory对象
     */
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
    
    /**
     * 执行数据库操作（带事务管理）
     * @param operation 数据库操作
     * @param <T> 返回类型
     * @return 操作结果
     */
    public static <T> T executeWithTransaction(SqlSessionOperation<T> operation) {
        SqlSession sqlSession = null;
        try {
            sqlSession = getSqlSession();
            T result = operation.execute(sqlSession);
            sqlSession.commit();
            return result;
        } catch (Exception e) {
            if (sqlSession != null) {
                sqlSession.rollback();
            }
            throw new RuntimeException("数据库操作失败", e);
        } finally {
            closeSqlSession(sqlSession);
        }
    }
    
    /**
     * 执行数据库操作（只读操作）
     * @param operation 数据库操作
     * @param <T> 返回类型
     * @return 操作结果
     */
    public static <T> T executeReadOnly(SqlSessionOperation<T> operation) {
        SqlSession sqlSession = null;
        try {
            sqlSession = getSqlSession();
            return operation.execute(sqlSession);
        } catch (Exception e) {
            throw new RuntimeException("数据库操作失败", e);
        } finally {
            closeSqlSession(sqlSession);
        }
    }
    
    /**
     * 数据库操作接口
     * @param <T> 返回类型
     */
    @FunctionalInterface
    public interface SqlSessionOperation<T> {
        T execute(SqlSession sqlSession) throws Exception;
    }
}
